import logging
from fastapi import APIRouter, Depends, HTTPException
from typing import List, Optional

from src.web.v1.dependencies import PipelineManagerWithRequestIdDep, get_service
from src.web.v1.services import Configuration
from src.web.v1.services.question_recommendation import QuestionRecommendationService
from pydantic import BaseModel, Field

router = APIRouter()
logger = logging.getLogger("wren-ai-service")

class Question(BaseModel):
    question: str
    category: Optional[str] = None

class QuestionRecommendationRequest(BaseModel):
    previous_questions: Optional[List[str]] = Field(default_factory=list)
    categories: Optional[List[str]] = Field(default_factory=list)
    max_questions: Optional[int] = 5
    max_categories: Optional[int] = 3

class QuestionRecommendationResponse(BaseModel):
    id: str
    status: str = Field(..., description="Status of the question recommendation: generating, finished, failed")
    questions: List[Question] = Field(default_factory=list, description="List of recommended questions")

@router.post("", response_model=QuestionRecommendationResponse)
async def generate_question_recommendation(
    request: QuestionRecommendationRequest,
    pipeline_manager: PipelineManagerWithRequestIdDep,
    configuration: Configuration = Depends(),
):
    """Generate question recommendations."""
    logger.info(f"Generating question recommendations with request: {request}")
    await pipeline_manager.run_async(
        "question_recommendation",
        mdl={},
        previous_questions=request.previous_questions,
        categories=request.categories,
        language=configuration.language,
        max_questions=request.max_questions,
        max_categories=request.max_categories,
    )
    return QuestionRecommendationResponse(id=pipeline_manager.id)

@router.get("/{id}", response_model=QuestionRecommendationResponse)
async def get_question_recommendation(id: str, service: QuestionRecommendationService = Depends(get_service)):
    logger.info(f"Getting question recommendation for id: {id}")
    
    # 获取资源
    resource = service[id]
    logger.info(f"Resource for id {id}: {resource}")
    
    # 获取问题列表
    questions = []
    if resource.response and "questions" in resource.response:
        # 将分类的问题转换为平面列表
        for category, category_questions in resource.response["questions"].items():
            for question in category_questions:
                if isinstance(question, dict) and "question" in question and "category" in question:
                    questions.append({
                        "question": question["question"],
                        "category": question["category"]
                    })
    
    logger.info(f"Found {len(questions)} questions for id {id}")
    
    # 构建响应
    response = QuestionRecommendationResponse(
        id=id,
        status=resource.status,
        questions=questions
    )
    
    logger.info(f"Returning response for id {id}: {response}")
    return response 